package org.huel.backend.service.impl;

import org.huel.backend.domain.entity.AbsencePrediction;
import org.huel.backend.mapper.AbsencePredictionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PredictionService {

    @Autowired
    private AbsencePredictionMapper absencePredictionMapper;

    /**
     * 获取某个学生的缺勤预测结果
     * @param studentId 学生ID
     * @return 预测结果列表
     */
    public List<AbsencePrediction> getStudentAbsencePredictions(String studentId) {
        return absencePredictionMapper.selectByStudentId(studentId);
    }

    /**
     * 获取高风险缺勤预测记录
     * @param threshold 风险阈值，例如0.7表示缺勤概率超过70%
     * @return 高风险预测记录
     */
    public List<AbsencePrediction> getHighRiskPredictions(float threshold) {
        return absencePredictionMapper.selectHighRiskAbsences(threshold);
    }

    /**
     * 添加或更新缺勤预测记录
     * @param absencePrediction 预测记录
     * @return 是否成功
     */
    public boolean saveAbsencePrediction(AbsencePrediction absencePrediction) {
        AbsencePrediction existing = absencePredictionMapper.selectByStudentIdAndCourseName(
                absencePrediction.getStudentId(),
                absencePrediction.getCourseName()
        );

        int result;
        if (existing == null) {
            result = absencePredictionMapper.insertAbsencePrediction(absencePrediction);
        } else {
            absencePrediction.setId(existing.getId());
            result = absencePredictionMapper.updateAbsencePrediction(absencePrediction);
        }

        return result > 0;
    }

    /**
     * 获取风险最高的N个学生
     * @param limit 数量限制
     * @return 预测记录列表
     */
    public List<AbsencePrediction> getTopRiskStudents(int limit) {
        return absencePredictionMapper.selectTopRiskStudents(limit);
    }




    /**
     * 获取前三名最可能缺勤的学生
     * @return 缺勤预测列表
     */
    public List<AbsencePrediction> getTopThreeAbsencePredictions() {
        return absencePredictionMapper.getTopAbsencePredictions(3);
    }

    /**
     * 根据课程获取前三名最可能缺勤的学生
     * @param courseName 课程名称
     * @return 缺勤预测列表
     */
    public List<AbsencePrediction> getTopThreeAbsencePredictionsByCourse(String courseName) {
        return absencePredictionMapper.getTopAbsencePredictionsByCourse(courseName, 3);
    }

    /**
     * 获取所有课程列表
     * @return 课程名称列表
     */
    public List<String> getAllCourses() {
        return absencePredictionMapper.getAllCourses();
    }

    /**
     * 根据学生ID获取预测信息
     * @param studentId 学生ID
     * @return 预测列表
     */
    public List<AbsencePrediction> getPredictionsByStudentId(String studentId) {
        return absencePredictionMapper.getPredictionsByStudentId(studentId);
    }
}